<template>
  <div class="cart-container">
    <!-- 购物车头部 -->
    <div class="cart-header">
      <h2>购物车</h2>
      <span class="item-count">共 {{ cartItems.length }} 件商品</span>
    </div>

    <!-- 购物车主体 -->
    <div class="cart-main" v-if="cartItems.length > 0">
      <!-- 表头 -->
      <div class="cart-table-header">
        <el-checkbox v-model="allSelected" @change="handleSelectAll"
          >全选</el-checkbox
        >
        <span class="column-product">商品信息</span>
        <span class="column-price">单价</span>
        <span class="column-quantity">数量</span>
        <span class="column-total">小计</span>
        <span class="column-action">操作</span>
      </div>

      <!-- 商品列表 -->
      <div class="cart-items">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <el-checkbox
            v-model="item.selected"
            @change="updateSelection"
          ></el-checkbox>
          <div class="item-info" @click="goToDetail(item.id)">
            <!-- 添加点击跳转 -->
            <el-image
              :src="item.picture"
              :alt="item.title"
              class="item-image"
              loading="lazy"
            ></el-image>
            <div class="item-details">
              <h3 class="item-title">{{ item.title }}</h3>
              <!-- 添加类名 -->
            </div>
          </div>
          <div class="item-price">¥{{ formatPrice(item.price) }}</div>
          <div class="item-quantity">
            <el-input-number
              v-model="item.quantity"
              :min="1"
              :max="99"
              @change="() => updateQuantity(item)"
              :controls-position="'right'"
            ></el-input-number>
          </div>
          <div class="item-subtotal">
            ¥{{ (item.price * item.quantity).toFixed(2) }}
          </div>
          <div class="item-actions">
            <el-popconfirm
              title="确定要删除这个商品吗？"
              @confirm="removeItem(item)"
            >
              <template #reference>
                <el-button type="text" class="delete-btn">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </div>

      <!-- 购物车底部 -->
      <div class="cart-footer">
        <div class="footer-left">
          <el-checkbox v-model="allSelected" @change="handleSelectAll"
            >全选</el-checkbox
          >
          <el-button type="text" @click="removeSelected"
            >删除选中商品</el-button
          >
        </div>
        <div class="footer-right">
          <div class="total-info">
            <span>已选择 {{ selectedCount }} 件商品</span>
            <span class="total-price"
              >合计：<em>¥{{ formatPrice(totalPrice) }}</em></span
            >
          </div>
          <el-button
            type="primary"
            :disabled="!selectedCount"
            @click="checkout"
          >
            结算
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空购物车展示 -->
    <div v-else class="empty-cart">
      <el-empty description="购物车是空的">
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const router = useRouter();
const cartItems = ref([]);

// 从localStorage加载购物车数据
onMounted(() => {
  console.log(1);
  const savedCart = JSON.parse(localStorage.getItem("cart") || "[]");
  cartItems.value = savedCart.map((item) => ({
    ...item,
    selected: true,
  }));
  console.log("savedCart");
  console.log(savedCart);
  console.log("cartItems");
  console.log(cartItems.value);
});

// 计算属性
const allSelected = computed({
  get: () =>
    cartItems.value.length && cartItems.value.every((item) => item.selected),
  set: (value) => cartItems.value.forEach((item) => (item.selected = value)),
});

const selectedCount = computed(
  () => cartItems.value.filter((item) => item.selected).length
);

const totalPrice = computed(() =>
  cartItems.value
    .filter((item) => item.selected)
    .reduce((sum, item) => sum + item.price * item.quantity, 0)
);

// 方法
const formatPrice = (price) => {
  if (typeof price !== 'number') {
    price = Number(price);
  }
  return price.toFixed(2);
};

const goToDetail = (productId) => router.push(`/product/${productId}`);

const updateQuantity = (item) => {
  if (item.quantity < 1) item.quantity = 1
  if (item.quantity > 99) item.quantity = 99
  updateCart()
  ElMessage.success('数量已更新')
}

const removeItem = (item) => {
  cartItems.value = cartItems.value.filter(i => i.id !== item.id)
  updateCart()
  ElMessage.success('商品已移除')
  
  // 如果购物车为空，自动跳转
  if (cartItems.value.length === 0) {
    setTimeout(() => {
      router.push('/')
    }, 1500)
  }
}

const handleSelectAll = (val) =>
  cartItems.value.forEach((item) => (item.selected = val));

const updateCart = () =>
  localStorage.setItem("cart", JSON.stringify(cartItems.value));

const removeSelected = () => {
  if (!selectedCount.value) {
    ElMessage.warning("请先选择商品");
    return;
  }
  cartItems.value = cartItems.value.filter((item) => !item.selected);
  updateCart();
  ElMessage.success("已删除选中商品");
};

const checkout = () => ElMessage.info("结算功能开发中...");
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  margin-bottom: 200px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cart-table-header {
  display: grid;
  grid-template-columns: 50px 3fr 1fr 1fr 1fr 80px;
  padding: 15px;
  background: #f5f5f5;
  align-items: center;
}

.cart-item {
  display: grid;
  grid-template-columns: 50px 3fr 1fr 1fr 1fr 80px;
  padding: 20px 15px;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.item-info {
  cursor: pointer;
  transition: all 0.3s ease;
}

.item-info:hover {
  opacity: 0.8;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
}

.item-title {
  margin: 0;
  font-size: 16px;
  color: #333;
  transition: color 0.3s ease;
}

.item-title:hover {
  color: #ff6700;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  margin-top: 20px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  text-align: right;
}

.total-price {
  margin-left: 20px;
}

.total-price em {
  color: #ff6700;
  font-style: normal;
  font-size: 20px;
  font-weight: bold;
}

.empty-cart {
  padding: 100px 0;
  text-align: center;
}

.delete-btn {
  color: #999;
  transition: color 0.3s ease;
}

.delete-btn:hover {
  color: #ff6700;
}

.item-quantity .el-input-number {
  width: 120px;
}

@media (max-width: 768px) {
  .cart-item {
    grid-template-columns: 1fr;
    gap: 15px;
    padding: 15px;
  }
  
  .item-info {
    flex-direction: row; /* 保持水平布局 */
    justify-content: flex-start;
    width: 100%;
  }

  .item-image {
    width: 60px;
    height: 60px;
  }

  .item-details {
    text-align: left;
    margin-left: 15px;
  }

  .item-price,
  .item-subtotal {
    text-align: left;
  }

  .item-quantity {
    display: flex;
    justify-content: flex-start;
  }

  .item-actions {
    display: flex;
    justify-content: flex-end;
  }
}
</style>